var formBilling = [];
var formShippin = [];
var formIdea = [];
var sum;
$(document).ready(function(){
    $('#faqText').jScrollPane({
        showArrows:true, 
        scrollbarWidth: 15, 
        arrowSize: 16
    });
    
    if ($("a[rel^='prettyPhoto']").length>0) {
        $("a[rel^='prettyPhoto']").prettyPhoto({
            social_tools:false,
            theme: 'dark_rounded',
            show_title: 'false'
        });
    }
    
    
    if ($("#bottomSignsList img").length >0) {
        $("#bottomSignsList img").rotate(-9);
    }
    if ($("#leftBlock img").length > 0) {
        $("#leftBlock").cycle({
            fx:   'fade',
            speed:  'slow',
            next: '.slideone',
            timeout:  6000,
            pause:1
        });
    }
    if ($("#middleBlock img").length > 0) {
        $("#middleBlock").cycle({
            fx:   'fade',
            speed:  'slow',
            next: '.slideone',
            timeout:  6000
        });
    }
    if ($("#bottomSignsList img").length > 0) {
        $('#slider-code').tinycarousel({ 
            display: 1, 
            controls: true,
            interval: true
        });
    }
    if ($("#customSigns input:radio").length) {
        $("input:radio, input:checkbox").uniform();
    }
    //sign show block
    if ($("#signShowChooseDelivery").length > 0) {
        $("input:radio").uniform();
//        $("#signShowChooseDelivery input").find(':checked').
        $("#signShowChooseDelivery input:radio").click(function(){
            $(".delivery .text").text($(this).attr('ref'));
            $(".delivery .rightCorner").text('$'+$(this).attr('price'));
            var price = parseFloat($(".signShowPriceSumm .sum:first").text());
            $(".signShowPriceSumm .sum:last").text(parseInt($(this).attr('price'))+price);
            $('input#deliveryPrice').val($(this).attr('price'));
        })
        //TODO: make disabled input
//        $('.resolution input').click(function(){
//            $('.resolution input').not(this).parents('.showSize').find('input').not('.resolution').prop('disabled',true)
//            console.log($('.resolution input').not(this).parents('.showSize').find('span').not('.resolution').find('input'))
//        })
    };
    $("#goBilling").click(function(){
        if ($('input[name="resolution"]:checked').length == 0) {
            alert ('Select resolution to procead');
            return false;
        }
        if ($('input[name="orientation"]:checked').length == 0) {
            alert ('Select orientation to procead');
            return false;
        }
        $('#showSignForm').submit();
        return false;
    });
    if($('#showDialog').val()==1) {
        showDialog('shippingDialog');
    }
    $('#orderLink').click(function(){
        $('#testForm').submit();
    })
    $('#finalizeLink').click(function(){
        var errorForm = false;
        $('#billinFormBlock input').each(function(i){
            $(this).css('border','1px solid #000');
            if ($(this).val() == '' || $(this).val() == formBilling[i]) {
                $(this).css('border','1px solid red');
                errorForm = true;
            }
        })
        $('#shippingFormBlock input').each(function(i){
            $(this).css('border','1px solid #999');
            if ($(this).val() == '' || $(this).val() == formShippin[i]) {
                $(this).css('border','1px solid red');
                errorForm = true;
            }
        })

        if (!errorForm) {
            var values = $('form#billing, form#shipping').serialize();
            var ref = (!$(this).hasClass('custom')) ? '/signs/billing/' : '/custom/billing/'
            $.ajax({
                url: ref,
                data: values,
                dataType: 'json',
                type: 'post',
                success: function(result) {
                    console.log(result)
                    if (result.response == true) {
                        window.location.assign('/commerce/checkout');
                    } else if (result.response == false) {
                        $.each(result.shipping,function(i){
                            $('#shipping-'+i).css('border','1px solid red');
                        })
                        $.each(result.billing,function(i){
                            $('#billing-'+i).css('border','1px solid red');
                        })
                    }
                }, 
                error: function(result) {
                    result = $.parseJSON(result.responseText);
    //                a = result.response
    //                console.log (a)
                    if (result.response == true) {
                        window.location.assign('/commerce/checkout');
                    } else if (result.response == false) {
                        $.each(result.shipping,function(i){
                            $('#shipping-'+i).css('border','1px solid red');
//                            console.log(i)
//                            console.log(this)
                        })
                        $.each(result.billing,function(i){
                            $('#billing-'+i).css('border','1px solid red');
//                            console.log(i)
//                            console.log(this)
                        })
                    }
                }

            })
        }
        return false;
    })
    
    //billing block
    $('#billinFormBlock input').each(function(i){
        if ($('#billinFormBlock input:hidden').length > 0) {
            formBilling[i] = '';
        } else {
            formBilling[i] = $(this).val();
        }
        
    })
    $('#shippingFormBlock input').each(function(i){
        if ($('#billinFormBlock input:hidden').length > 0) {
            formShippin[i] = '';
        } else {
            formShippin[i] = $(this).val();
        }
    })
    $('#shippingFormBlock input').each(function(i){
        $(this).focus(function(){
            $(this).css({'border':'1px solid #999','color':'#000','font-style':'normal'});
            if ($(this).val() == formShippin[i]) {
                $(this).val('');
            }
        })
        $(this).blur(function(){
            if ($(this).val() == '') {
                $(this).val(formShippin[i]);
                $(this).css({'border':'1px solid red','color':'#999','font-style':'italic'});
            }
        })
    }) 
    $('#billinFormBlock input').each(function(i){
        
        $(this).focus(function(){
            $(this).css({'border':'1px solid #999','color':'#000','font-style':'normal'});
            if ($(this).val() == formShippin[i]) {
                $(this).val('');
            }
        })
        $(this).blur(function(){
            $(this).css('border','1px solid #999');
            if ($(this).val() == '') {
                $(this).val(formShippin[i]);
                $(this).css({'border':'1px solid red','color':'#999','font-style':'italic'});
            }
        })
    }) 
    $('#sameCheckbox').click(function(){
        if ($('#sameCheckbox:checked').length > 0) {
            var index = $('#billing-state').find(':selected').index();
            $('#shipping-state').find('option').eq(index).attr('selected', true);
            $.each($('#billinFormBlock input'), function(){
                var str = this.id.split('-');
                $('#shipping-'+str[1]).attr('value',$(this).attr('value'));
            })
        }
    })
    $('#billinFormBlock input').keyup(function(){
        if ($('#sameCheckbox:checked').length > 0) {
            var str = this.id.split('-');
            $('#shipping-'+str[1]).attr('value',$(this).attr('value'));
        }
    })
    $('#billinFormBlock #billing-state').change(function(){
        if ($('#sameCheckbox:checked').length > 0) {
            var index = $(this).find(':selected').index();
            $('#shipping-state').find('option').eq(index).attr('selected', true);
        }
    })
    //Sign Idea
    formIdea[0] = $('#ideaForm input').val();
    formIdea[1] = $('#ideaForm textarea').val();
    $('.sendForm').live('click', function(){
        var inputValue = $('#ideaForm input').val();
        if ($('#ideaForm input').val() == formIdea[0]) {
            $('#ideaForm input').val('');
        }
        if ($('#ideaForm textarea').val() == '' || $('#ideaForm textarea').val() == formIdea[1]) {
            $('#ideaForm textarea').css('border','1px solid red');
            $('#ideaForm input').val(inputValue);
            return false;
        }
        
        $.ajax({
            url:'/signs/sendidea/',
            data:$('#ideaForm').serialize(),
            type:'post',
            dataType:'json',
            success:function() {
                alert ('Thanks for sign idea.')
            }
        })
//        console.log($('#ideaForm').serialize());
    })
    $('#ideaForm input, #ideaFormDialog input').focus(function(){
        if ($(this).val() == formIdea[0]) {
            $(this).val('');
            $(this).css({'border':'1px solid #999','font-style':'normal','color':'#000'})
        }
    })
    $('#ideaForm input, #ideaFormDialog input').blur(function(){
        if ($(this).val() == '') {
            $(this).val(formIdea[0]);
            $(this).css({'border':'1px solid #999','font-style':'italic','color':'#B3B3B3'})
        }
    })
    $('#ideaForm textarea, #ideaFormDialog textarea').focus(function(){
        if ($(this).text() == formIdea[1] || $('#ideaForm textarea').val() == formIdea[1]) {
            $(this).text('').val('');
            $(this).css({'border':'1px solid #999','font-style':'normal','color':'#000'})
        }
    })
    $('#ideaForm textarea, #ideaFormDialog textarea').blur(function(){
        if ($(this).val() == '') {
            $(this).text(formIdea[1]).val(formIdea[1]);
            $(this).css({'border':'1px solid #999','font-style':'italic','color':'#B3B3B3'})
        }
    })
    
    
    //Checkout Quantity
    $('.quantyty').keyup(function(){
        var quantity = parseInt($(this).val(), 10)
        $.ajax({
            url:'/commerce/updatequant/',
            data:{
                'itemId':$(this).attr('data'),
                'quantity':quantity,
                'section':$(this).attr('dataSection')
            },
            type:'post',
            dataType:'json',
            success:function() {
//                alert ('Quantity change.')
            }
        })
    })
    
    //Check code
    sum = parseFloat($('.total .sum').text());
    $('#checkCode').click(function(){
        if ($('#discountCode').val() == '') {
            alert ('Input discount code');
            $('#discountCode').focus()
        }
        var quantity = parseInt($(this).val(), 10)
        $.ajax({
            url:'/signs/discount/',
            data:{
                'code':$('#discountCode').val()
            },
            type:'post',
            dataType:'json',
            success:function(data) {
                if (data.result==true) {
                    var result = sum-parseFloat(data.discount)
                    $('.total .sum').text(result.toFixed(2));
                    $('.discount').show().find('.sum').text(data.discount)
                } else {
                    alert('Whong discount code.');
                    $('#discountCode').focus().val('')
                }
            }
        })
        return false;
    })
    
    //checkCode
    
})
